#include "mytcpserver.h"
#include "tcpserver.h"
#include <QDebug>


MyTcpServer::MyTcpServer()
{

}

MyTcpServer &MyTcpServer::getInstance()
{
    static MyTcpServer instance;
    return instance;
}

void MyTcpServer::incomingConnection(qintptr socketDescriptor) // 产生一个socket ，传入收发数据
{
    qDebug()<<"new client connected";
    MyTcpSocket *pTcpSocket = new MyTcpSocket;
    pTcpSocket->setSocketDescriptor(socketDescriptor);
    m_tcpSocketList.append(pTcpSocket);//链接，数据收发
    //退出登录需要删除socket，因为客户端下线，没有用了，不然会造成资源浪费
    //同时还需要将在线状态设置为非在线状态
    connect(pTcpSocket,SIGNAL(offLine(MyTcpSocket*)),this,SLOT(deleteSocket(MyTcpSocket*)));

}

void MyTcpServer::resend(const char *pername, PDU *pdu)
{
    //找到socket
    if(pername == nullptr || pdu == nullptr) return;
    QString strName = pername;
    for(int i = 0;i< m_tcpSocketList.size();++i)
    {
        if(strName == m_tcpSocketList.at(i)->getName())//名字找到对应的socket
        {
            m_tcpSocketList.at(i)->write((char*)pdu,pdu->uiPDULen);
            break;
        }
    }
}

void MyTcpServer::deleteSocket(MyTcpSocket *mysocket)//将socket删除
{
    QList<MyTcpSocket*>::iterator iter = m_tcpSocketList.begin();//用迭代器遍历这个链表
    for(;iter!=m_tcpSocketList.end();iter++)
    {
        if(mysocket == *iter)
        {
            delete *iter;//首先将指向的对象删除掉
            *iter = nullptr;
            m_tcpSocketList.erase(iter);
            break;
        }
    }
    for(int i = 0;i< m_tcpSocketList.size();++i)
    {
        qDebug() << m_tcpSocketList.at(i)->getName();
    }

}

